// mängijad
var players;
// mängu info
var game;
// muutuja, millega intervalliga meetodi väljakutsed lõpetada
var intervalID;
// aktiivne intervall
var activeInterval;
// kas lubada klikke
var allowClick = false;
// mängija, kes pole bot
var HUMAN_PLAYER = 6;

CARD_VALUE = {
	    '2'  : '2',
	    '3'  : '3',
	    '4'  : '4',
	    '5'  : '5',
	    '6'  : '6',
	    '7'  : '7',
	    '8'  : '8',
	    '9'  : '9',
	    'T'  : '10',
	    'J'  : '11',
	    'Q'  : '12',
	    'K'  : '13',
	    'A'  : '14'
	  };

function Game() {
	this.bankSize = 0;
	this.deck = new Deck();
	this.loc = -1;
	this.raiseLimit = 3;
	this.raiseBy = 2;
	this.highestBet = 0;
	this.isRoundOver = false;
	this.round = 0;
	this.dealerLocation = 0;
	this.SBLocation = 0;
	this.BBLocation = 0;
	this.createCards = function() {
		this.deck.createDeck();
	}
	this.reset = function() {
		this.raiseBy = 2;
		this.raiseLimit = 3;
		this.round = 0;
		this.bankSize = 0;
		this.isRoundOver = false;
	}
	this.dealFlop = function() {
		var paths = new Array(3);
		paths[0] = "images/" + this.deck.deck[18].suit + "/"
		+ this.deck.deck[18].value + ""
		+ this.deck.deck[18].suit + ".png";
		paths[1] = "images/" + this.deck.deck[19].suit + "/"
		+ this.deck.deck[19].value + ""
		+ this.deck.deck[19].suit + ".png";
		paths[2] = "images/" + this.deck.deck[20].suit + "/"
		+ this.deck.deck[20].value + ""
		+ this.deck.deck[20].suit + ".png";
		
		for (i = 1; i < 4; i++) {
			$('#flop' + i).children(':first-child')
			.attr("src", paths[i - 1]);
			$('#flop' + i).css("visibility", "visible");
		}
	}
	this.dealTurn = function() {
		var path = "images/" + this.deck.deck[21].suit + "/"
		+ this.deck.deck[21].value + ""
		+ this.deck.deck[21].suit + ".png";
		
		$('#turn').children(':first-child')
		.attr("src", path);
		$('#turn').css("visibility", "visible");
	}
	this.dealRiver = function() {
		var path = "images/" + this.deck.deck[22].suit + "/"
		+ this.deck.deck[22].value + ""
		+ this.deck.deck[22].suit + ".png";
		
		$('#river').children(':first-child')
		.attr("src", path);
		$('#river').css("visibility", "visible");
	}
	this.cleanUp = function() {
		$('#pot').html("<b>Pot:</b> " + this.bankSize);
		$('#pot').css("visibility", "visible");
		calculateChips(0, this.bankSize);
		resetChipImages(1);
		hideChipInfo();
	}
}

function Deck() {
	this.deck = new Array();
	this.createDeck = function() {
		var i;

		for (i = 1; i < 14; i++) {
			this.deck.push(gaga.createCard(i, 'H'));
			this.deck.push(gaga.createCard(i, 'D'));
			this.deck.push(gaga.createCard(i, 'C'));
			this.deck.push(gaga.createCard(i, 'S'));
		}
	}

	// Fisher-Yates shuffle algorithm:
	// http://sedition.com/perl/javascript-fy.html
	this.shuffle = function() {
		var i = 52;
		while (--i) {
			var j = Math.floor(Math.random() * (i + 1));
			var tempi = this.deck[i];
			var tempj = this.deck[j];
			this.deck[i] = tempj;
			this.deck[j] = tempi;
		}
	}
}

function Player(player_no) {
	this.no = player_no;
	this.stack = 100;
	this.bet = 0;
	this.totalBet = 0;
	this.active = true;
	this.fold = function() {
		this.active = false;
		this.hideCards();
		outputText(" folded.", this.no);
	}
	this.call = function() {
		this.decreaseStack(game.highestBet - this.bet);
		if(this.bet > 0)
			outputText(" called €" + this.bet + ".", this.no);
		else
			outputText(" checked.", this.no);
	}
	this.raise = function() {
		game.highestBet = game.highestBet + game.raiseBy;
		this.decreaseStack(game.highestBet - this.bet);
		game.raiseLimit--;
		if(this.bet == game.raiseBy)
			outputText(" bet €" + this.bet + ".", this.no);
		else
			outputText(" raised €" + this.bet + ".", this.no);
	}
	this.decreaseStack = function(amount) {
		if(amount >= this.stack) {
			amount = this.stack;
		}
		this.stack = this.stack - amount;
		this.bet = this.bet + amount;
		this.totalBet = this.totalBet + amount;
		this.repaint();
	}
	this.increaseStack = function(amount) {
		this.stack = this.stack + amount;
		$('#stack' + this.no).html(this.stack);
	}
	this.repaint = function() {
		$('#stack' + this.no).html(this.stack);
		$('#chipinfo' + this.no).html('<b>Chips:</b> '
				+ this.bet);
		$('#chipinfo' + this.no).css("visibility", "visible");
		calculateChips(this.no, this.bet);
	}
	this.hideCards = function() {
		$('#card' + this.no + '_1').children(':first-child').animate({
		    marginBottom: "-75"
		  }, 500).fadeOut();
		$('#card' + this.no + '_2').children(':first-child').animate({
		    marginBottom: "-75"
		  }, 500).fadeOut();
	}
	this.showCards = function() {
		var paths = new Array(2);
		paths[0] = "images/" + game.deck.deck[this.no - 1].suit + "/"
				+ game.deck.deck[this.no - 1].value + ""
				+ game.deck.deck[this.no - 1].suit + ".png";
		paths[1] = "images/" + game.deck.deck[this.no + 8].suit + "/"
				+ game.deck.deck[this.no + 8].value + ""
				+ game.deck.deck[this.no + 8].suit + ".png";

		var i;

		for (i = 1; i < 3; i++) {
			$('#card' + this.no + '_' + i).children(':first-child')
					.attr("src", paths[i - 1]);
		}
	}
	this.makeDecision = function() {
		if(!this.active)
			return;
		var rand = Math.random();
		if (rand < 0.2) {
			this.fold();
		} else if (rand >= 0.2 && rand <= 0.8) {
			this.call();
		} else {
			if (game.raiseLimit > 0 && this.stack >= game.highestBet + game.raiseBy - this.bet) {
				this.raise();
			} else {
				this.call();
			}
		}
	}
}

// chatboxi teksti lisamine
function addText() {
	var input = $("#chatinput").val();
	if (input != "")
		$("#textarea2").append("<b>You: </b>" + input + "<br />");
	$("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
	$("#chatinput").val("");
	setTimeout('botReply()', 1000);
}

// bottide suvaline vastus
function botReply() {
	var random;
	var reply;
	var gamesplayed = Math.floor(Math.random() * 12 + 1);
	// TODO : add more replies for bots
	var replies = ["Nice day, isn't it?", "You are bluffing.", 
	               "You will be cleaned soon.", "This is my lucky day.",
	               "Your luck will soon run out.", "What's up?",
	               "Don't be afraid to raise :)", "I can see right through your plans.",
	               "Do you feel lucky?", "Easy money for me!", "Give up and I'll save you from embarrassment.",
	               "Your chips will be mine.", "You think you are professional?", "Are you ready to lose your money?",
	               "Nothing beats a good poker game, does it?", "I bet you lose today :P", 
	               "I heard you have tendency to lose :D", "You play like an amateur.",
	               "I have seen better players.", "I'm totally going to beat you.", "Is this your first time?",
	               "I recommend you to read some poker rules before playing with us.",
	               "Can't handle my playing style?", "Where are you from?", 
	               "I have once played on World Series of Poker.",
	               "I have won my last "+ gamesplayed +" games in a row.",
	               "Even my dog can play better than you."
	               ];
	random = Math.floor(Math.random() * replies.length);
	reply = replies[random];
	do {
		random = Math.floor(Math.random() * 9 + 1);
	} while(random == HUMAN_PLAYER);
	
	$("#textarea2").append("<b>Player " + random + ": </b>" + reply + "<br />");
	$("#textarea2").scrollTop($("#textarea2")[0].scrollHeight);
}

// Enteri vajutusel käivitakse addText funktsioon
function pressEnter(myfield, e) {
	var keycode;
	if (window.event)
		keycode = window.event.keyCode;
	else if (e)
		keycode = e.which;
	else
		return true;
	if (keycode == 13) {
		addText();
		return false;
	} else
		return true;
}

function outputText(text, initiator) {
	var str;
	if(initiator != HUMAN_PLAYER) {
		str = "Player " + initiator;
	} else {
		str = "You";
	}
	$("#textarea").append("<i><b>" + str + "</b>" + text + "<i>" + "<br />");
	$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
}

// Koodiosa kasutaja fold jaoks
function showFold() {
		players[HUMAN_PLAYER - 1].fold();
		afterMove();
		return true;
}
// Koodiosa kasutaja call jaoks, hetkel flop
function showCall() {
		players[HUMAN_PLAYER - 1].call();
		afterMove();
		return true;
}

// kasutaja raise
function showRaise() {
		players[HUMAN_PLAYER - 1].raise();
		afterMove();
		return true;
}

// see, mis tehakse pärast mängija käiku
function afterMove() {
	findFirstActive();
	disableButtons();
	resumePlay();
}

// mängu jätkamine
function resumePlay() {
	if(!activeInterval) {
		activeInterval = true;
		intervalID = setInterval('playRound()', 1000);
	}
}

// diiler, sb, bb nuppude varjamine
function hideButtons() {
	$('#dealer' + game.dealerLocation).css("visibility", "hidden");
	$('#dealer' + game.SBLocation).css("visibility", "hidden");
	$('#dealer' + game.BBLocation).css("visibility", "hidden");
}

// diiler, sb, bb nuppude joonistamine
function paintButtons() {
	$('#dealer' + game.SBLocation).css("visibility", "visible")
		.children(':first-child').attr("src", "images/nupud/SB.png");
	$('#dealer' + game.BBLocation).css("visibility", "visible")
		.children(':first-child').attr("src", "images/nupud/BB.png");
	$('#dealer' + game.dealerLocation).css("visibility", "visible")
	.children(':first-child').attr("src", "images/nupud/D.png");
}

// diiler, sb, bb nuppude liigutamine 1 koha võrra edasi
function moveButtons() {
	game.loc = game.dealerLocation;
	findFirstActive();
	game.dealerLocation = game.loc;
	findFirstActive();
	game.SBLocation = game.loc;
	findFirstActive();
	game.BBLocation = game.loc;
}

// Kood dealer, SB ja BB nupu juhuslikuks paigutamiseks mängu alguses
function randomDealer() {
	if (game.dealerLocation > 0) {
		hideButtons();
	}

	game.dealerLocation = Math.floor(Math.random() * 9 + 1);

	if (game.dealerLocation == 8) {
		game.SBLocation = 9;
		game.BBLocation = 1;
	} else if (game.dealerLocation == 9) {
		game.SBLocation = 1;
		game.BBLocation = 2;
	} else {
		game.SBLocation = game.dealerLocation + 1;
		game.BBLocation = game.dealerLocation + 2;
	}

	paintButtons();
}

// hack, et Firefoxis töötaks
function defineObjectCreate() {
	if (typeof Object.create === 'undefined') {
		Object.create = function(o) {
			function F() {
			}
			F.prototype = o;
			return new F();
		};
	}
}

// mängijate loomine
function initPlayers() {
	players = new Array();
	for(var i = 1; i < 10; i++) {
		players.push(new Player(i));
	}
}


$(document).ready(function() {
    disableButtons();
});

// kood uue mängu alustamiseks
function startGame() {
	defineObjectCreate();
	$("#start").hide();
	$("#end").show();
	
	disableButtons();
	
	game = new Game();
	initPlayers();
	resetCardImages();
	resetChipImages(0);
	resetStacks();
	restartActivity();
	resetBets();
	hideChipInfo();
	hidePotSize();
	initCards();
	setCardsVisible();

	randomDealer();
	setBlinds();

	if(game.deck.deck.length == 0) {
		game.createCards();
	}

	game.deck.shuffle();

	players[HUMAN_PLAYER - 1].showCards();

	setCardsHidden();
	game.loc = game.BBLocation + 1;
	
	activeInterval = false;
	resumePlay();
	$("#textarea").append("<font color=blue><b>New game has started."+"</b></font><br/>");
	$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
}

// kõik, mis toimub mängus
function playRound() {
	if(checkCondition()){
		if (game.loc > 9) {
			game.loc = 1;
		}

		players[game.loc - 1].makeDecision();
		
		findFirstActive();
	} else {
		activeInterval = false;
		clearInterval(intervalID);
		if(game.loc == HUMAN_PLAYER && equalBet()) {
			game.isRoundOver = true;
		} else if(!game.isRoundOver) {
			enableButtons();
		}
	}


	if (game.isRoundOver) {		
		endBettingRound();
	
		if(game.round < 4) {
			resumePlay();
		} else {
			determineWinner();
			allowClick = true;
			$(":focus").blur();
			$("#info").css("visibility", "visible");
		}
	}
}

// see, mis toimub pärast riverit või kui vaid 1 mängija on järel
function finishGame() {
	
	game.reset();

	resetTotalBet();
	resetCardImages();
	resetChipImages(0);
	removeCleaned();
	restartActivity();
	resetBets();
	hideChipInfo();
	hidePotSize();
	setCardsVisible();
	
	if(countActive() <= 1){
		for(var i = 0; i < 9; i++){
			if(players[i].active){
				if(players[i].no != HUMAN_PLAYER)
					alert("Game over. Player " + (i + 1) + " won.");
				else
					alert("Game over. You won!");
			}
		}
		endGame();
		return;
	}
	
	if(!players[HUMAN_PLAYER - 1].active) {
		alert("Game over. You ran out of money!");
		endGame();
		return;
	}
	
	hideButtons();
	moveButtons();
	paintButtons();
	
	setBlinds();
	
	game.deck.shuffle();

	if(players[HUMAN_PLAYER - 1].active)
		players[HUMAN_PLAYER - 1].showCards();

	setCardsHidden();
	findFirstActive();
	resumePlay();
}

// võitja kindlaks tegemine
var count_sidepot;
function determineWinner() {
	if (countPlayersLeft() > 1) {
		for ( var i = 0; i < 9; i++) {
			if (players[i].active)
				players[i].showCards();
		}
		var bets = new Array();
		for(var i = 0; i < 9; i++) {
			bets.push(players[i].totalBet);
		}
		var discard = new Array();
		var minimum = 0;
		count_sidepot = 0;
		
		do {
			var winner = checkHands(discard);
			var winningPlayers = new Array();
			winningPlayers.push(winner);
			
			for(var i = 0; i < winner.equal.length; i++) {
				winningPlayers.push(winner.equal[i]);
			}
			
			winningPlayers = sortPlayerHands(winningPlayers);
			var pots = calcPots(winningPlayers, bets, minimum);
			if(players[winningPlayers[winningPlayers.length - 1].player_no - 1].totalBet > minimum)
				minimum = players[winningPlayers[winningPlayers.length - 1].player_no - 1].totalBet;
			var winSizes = new Array(pots.length);
			var sum = 0;
			
			for(var i = 0; i < pots.length; i++) {
				sum = 0;
				for(var j = 0; j <= i; j++) {
					sum += Math.floor(pots[j] / (pots.length - j));
				}
				winSizes[i] = sum;
			}

			showWinner(winningPlayers, winSizes, 0);

			for(var i = 0; i < winningPlayers.length; i++) {
				players[winningPlayers[i].player_no - 1].increaseStack(winSizes[i]);
				discard.push(winningPlayers[i].player_no);
			}
			count_sidepot++;
		} while(!moneyDepleted(bets));	
		
	} else {
		var winner;
		for(var i = 0; i < 9; i++) {
			if(players[i].active) {
				winner = players[i];
				break;
			}
		}
		
		if(winner.no != HUMAN_PLAYER) {
			//alert("Player " + winner.no + " won.");
			$("#textarea").append("<font color=red>Player " + winner.no + " won the main pot (€" + game.bankSize + ").</font><br />");
			$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
		}		
		else {
			//alert("You won.");
			$("#textarea").append("<font color=red>You won the main pot (€" + game.bankSize + ").</font><br />");
			$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
		}	
		
		players[winner.no - 1].increaseStack(game.bankSize);
	}
}

// võitja väljastamine
function showWinner(hands, wins, minimum) {
	var win_no = countWins(wins);
	if(win_no == 0) {
		count_sidepot--;
		return;
	}
		
	var potName = "";
	var str = "";
	var tmp;
	var winSize = -1;
	var min = 0;
	var changed = false;
	var line = -1;
	if(hands.length > 1) {
		if(count_sidepot == 0) {
			potName = "Main pot ";
		} else {
			potName = "Side pot " + count_sidepot + " ";
		}
		for(var i = 0; i < hands.length; i++) {
			if(winSize > 0 && wins[i] != winSize && !changed) {
				changed = true;
				line = i;
				min = winSize;
			}
			if(wins[i] > 0) {
				winSize = wins[i];
				tmp = hands[i];
				if(hands[i].player_no != HUMAN_PLAYER)
					str += "Player " + hands[i].player_no + ", ";
				else
					str += "You, ";
			}
		}
		if(win_no > 1) {
			str = str.substring(0, str.length - 2);
			$("#textarea").append("<font color=red>" + potName + "(€" + sumWins(wins, minimum) + ") shared between " + str + ": " + hands[0].identify().name + ".</font><br/>");
			$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
			//alert(potName + "(€" + sumWins(wins, minimum) + ") shared between " + str + "\n" + hands[0].identify().name);
		} else if (win_no == 1) {
			showWinner([tmp], wins, minimum);
		}
		
		if(line != -1) {
			count_sidepot++;
			showWinner(hands.slice(line, hands.length), wins.slice(line, wins.length), min);
		}
		return;
	}
	
	if(count_sidepot == 0) {
		potName = "main pot ";
	} else {
		potName = "side pot " + count_sidepot + " ";
	}
	
	str = hands[0].cards[0].value + " " + hands[0].cards[0].suit + ", " +
		hands[0].cards[1].value + " " + hands[0].cards[1].suit + ", " +
		hands[0].cards[2].value + " " + hands[0].cards[2].suit + ", " +
		hands[0].cards[3].value + " " + hands[0].cards[3].suit + ", " +
		hands[0].cards[4].value + " " + hands[0].cards[4].suit;
	
	if(hands[0].player_no != HUMAN_PLAYER) {
		$("#textarea").append("<font color=red>Player " + hands[0].player_no + " won " + potName + "(€" + sumWins(wins, minimum) + "). " + hands[0].identify().name + ": " + str + ".</font><br/>");
		$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
		//alert("Player " + hands[0].player_no + " won " + potName + "(€" + sumWins(wins, minimum) + ").\n" + hands[0].identify().name + ": " + str);
	}	
	else {
		$("#textarea").append("<font color=red>You won " + potName + "(€" + sumWins(wins, minimum) + "). " + hands[0].identify().name + ": " + str + ".</font><br/>");
		$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
		//alert("You won " + potName + "(€" + sumWins(wins, minimum) + ").\n" + hands[0].identify().name + ": " + str);
	}
}

// kokku liitmine, palju mingis potis raha on
function sumWins(wins, minimum) {
	var sum = 0;
	var start = 0;
	for(var i = 0; i < wins.length; i++) {
		if(start == 0 && wins[i] != 0)
			start = wins[i];
		if(wins[i] == start)
			sum += wins[i] - minimum;
		else
			sum += start - minimum;
	}
	return sum;
}

// mitmel võrdse käega mängijal on midagi võita
function countWins(wins) {
	var count = 0;
	for(var i = 0; i < wins.length; i++) {
		if(wins[i] > 0)
			count++;
	}
	return count;
}

// kontroll, kas raha on otsas
function moneyDepleted(bets) {
	for(var i = 0; i < 9; i++) {
		if(bets[i] != 0)
			return false;
	}
	return true;
}

// main pot ja side pot leidmine
function calcPots(hands, bets, minimum) {
	var pots = new Array(hands.length);
	var bet;
	var diff;
	
	for(var i = 0; i < pots.length; i++) {
		pots[i] = 0;
		bet = players[hands[i].player_no - 1].totalBet;
		if(bet <= minimum)
			continue;
		for(j = 0; j < 9; j++) {
			if(bet >= players[j].totalBet) {
				pots[i] += bets[j];
				bets[j] = 0;
			} else {
				if(i == 0 || (i > 0 && players[hands[i - 1].player_no - 1].totalBet <= minimum)) {
					pots[i] += bet - minimum;
					bets[j] -= bet - minimum;
				}
				else {
					diff = bet - players[hands[i - 1].player_no - 1].totalBet;
					pots[i] += diff;
					bets[j] -= diff;
				}
			}
		}
	}
	
	return pots;
}

// paigutab mängijate käed panuse suurenemise järjekorda
function sortPlayerHands(playerHands) {
	if(playerHands.length < 2)
		return playerHands;
	
	var temp;
	var changed = true;
	while(changed) {
		changed = false;
		for(var i = 1; i < playerHands.length; i++) {
			if(players[playerHands[i].player_no - 1].totalBet < players[playerHands[i-1].player_no - 1].totalBet){
				temp = playerHands[i];
				playerHands[i] = playerHands[i - 1];
				playerHands[i - 1] = temp;
				changed = true;
			}
		}
	}
	
	return playerHands;
}

// panustamise vooru lõpp
function endBettingRound() {
	for(var i = 0; i < 9; i++) {
		game.bankSize += players[i].bet;
		players[i].bet = 0;
	}
	game.cleanUp();
	
	if(countPlayersLeft() <= 1) {
		game.round = 4;
		activeInterval = false;
		clearInterval(intervalID);
		return;
	}
	
	if(countActive() == 0) {
		activeInterval = false;
		clearInterval(intervalID);
	}
	
	game.loc = game.dealerLocation;
	findFirstActive();
	game.raiseLimit = 4;
	game.highestBet = 0;
	game.isRoundOver = false;
	game.round++;
	switch(game.round) {
	case 1: game.dealFlop();
		break;
	case 2: game.dealTurn();
			game.raiseBy += 2;
		break;
	case 3: game.dealRiver();
		break;
	default: 
		break;
	}
}

// esimese mängija leidmine, kes saab käiku teha
function findFirstActive() {
	var start = game.loc;
	do {
		game.loc++;
		if (game.loc > 9) {
			game.loc = 1;
		}
		if(game.loc == start) {
			game.isRoundOver = true;
			break;
		}
	} while(!players[game.loc-1].active || players[game.loc -1].stack <= 0);
}

// kontroll, kas mängu tsükliga jätkata või ei
function checkCondition() {
	if((game.loc != HUMAN_PLAYER || !players[HUMAN_PLAYER - 1].active) && !equalBet())
		return true;
	return false;
}

// kontrollib, kas kõigil mängu jäänutel on max panus
function equalBet() {
	if(countActive() == 1) {
		if(canRaise())
			return false;
		return true;
	}
	var comp = game.highestBet;
	if(comp == 0 && !isAllCheck())
		return false;

	for ( var i = 0; i < 9; i++) {
		if (players[i].bet != comp && players[i].active && players[i].stack > 0)
			return false;
	}
	game.isRoundOver = true;
	return true;
}

// kas ainukese mängu jääja peab oma panust tõstma
function canRaise() {
	for(var i = 0; i < 9; i++) {
		if(players[i].active && players[i].stack > 0 && players[i].bet != game.highestBet)
			return true;
	}
	return false;
}

// kas kõik checkisid
function isAllCheck() {
	for(var i = 0; i < 9; i++) {
		if(players[i].active && $('#chipinfo' + (i + 1)).css("visibility") == "hidden" && players[i].stack > 0) {
			return false;
		}
	}
	return true;
}

// kaardid nähtavaks (ainult mängu alguses)
function initCards() {
	for(var i = 1; i < 10; i++) {
		$('#cards_' + i).css("visibility", "visible");
	}
}

// kaartide nähtavaks tegemine
function setCardsVisible() {
	for (var i = 1; i < 10; i++) {
		if(players[i - 1].active) {
			$('#card' + i + '_1').children(':first-child').css("margin-bottom", "-75px").fadeIn().animate({
			    marginBottom: "+=75"
			  }, 1000);
			$('#card' + i + '_2').children(':first-child').css("margin-bottom", "-75px").fadeIn().animate({
			    marginBottom: "+=75"
			  }, 1000);
		}	
	}
}
// lauapealsete kaartide peitmine
function setCardsHidden() {
	$('#flop1').css("visibility", "hidden");
	$('#flop1').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#flop2').css("visibility", "hidden");
	$('#flop2').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#flop3').css("visibility", "hidden");
	$('#flop3').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#turn').css("visibility", "hidden");
	$('#turn').children(':first-child').attr("src", "images/nupud/tcard.png");
	$('#river').css("visibility", "hidden");
	$('#river').children(':first-child').attr("src", "images/nupud/tcard.png");
}
// žetoonide kogus laual -> nähtamatu
function hideChipInfo() {
	var i;

	for (i = 1; i < 10; i++) {
		$('#chipinfo' + i).css("visibility", "hidden");
	}
}

// peida panga suurus
function hidePotSize() {
	$('#pot').css("visibility", "hidden");
}

// SB ja BB žetoonide tekitamine lauale...
function setBlinds() {
	players[game.SBLocation - 1].decreaseStack(1);
	players[game.BBLocation - 1].decreaseStack(2);
	game.highestBet = 2;
}

// bet, fold, check nuppude disable
function disableButtons() {
	$("#button2").children(":first-child").attr("disabled", true);
	$("#button3").children(":first-child").attr("disabled", true);
	$("#button4").children(":first-child").attr("disabled", true);
}

// bet, fold, check nuppude enable
function enableButtons() {
	$("#button2").children(":first-child").attr("disabled", false);
	$("#button3").children(":first-child").attr("disabled", false);
	if(game.raiseLimit > 0 && players[HUMAN_PLAYER - 1].stack >= game.highestBet + game.raiseBy - players[HUMAN_PLAYER - 1].bet)
		$("#button4").children(":first-child").attr("disabled", false);
}

// kogu raundi panuse reset
function resetTotalBet() {
	for(var i = 0; i < 9; i++) {
		players[i].totalBet = 0;
	}
}

// kood tagakülje piltide taastamiseks
function resetCardImages() {
	var i;
	var j;

	for (i = 1; i < 10; i++) {
		for (j = 1; j < 3; j++) {
			if (i == HUMAN_PLAYER)
				break;
			$('#card' + i + '_' + j).children(":first-child")
					.attr("src", "images/nupud/tagakylg.png");
		}
	}

}

// mängijate eemaldamine, kellel on raha otsas
function removeCleaned() {
	for ( var i = 0; i < 9; i++) {
		if(players[i].stack <= 0){
			players[i].active = false;
			$('#cards_' + (i + 1)).css("visibility", "hidden");
		}		
	}
}

// aktiivsuse restart
function restartActivity() {
	for ( var i = 0; i < 9; i++) {
		if(players[i].stack > 0)
			players[i].active = true;
	}
}

// žetoonipiltide eemaldamine
function resetChipImages(start) {
	for (i = start; i < 10; i++) {
		$('#chips' + i).html("");
	}
}

// anda igale mängijale uuesti 100 raha
function resetStacks() {
	var i;

	for (i = 1; i < 10; i++) {
		players[i - 1].stack = 100;
		$('#stack' + i).html("100");
	}
}

// panuste nullimine
function resetBets() {
	var i;

	for (i = 0; i < 9; i++) {
		players[i].bet = 0;
	}
}

// mängijate loendamine, kes saavad käike teha
function countActive() {
	var res = 0;
	for(var i = 0; i < 9; i++) {
		if(players[i].active && players[i].stack > 0)
			res++;
	}
	
	if(res <= 1 && !canRaise()) {
		game.isRoundOver = true;
	}
	return res;
}

// mängijate loendamine, kes on veel mängus alles (aga ei pruugi saada käiku
// teha)
function countPlayersLeft() {
	var res = 0;
	for(var i = 0; i < 9; i++) {
		if(players[i].active)
			res++;
	}
	
	return res;
}

// mängijate 5-ste käte võrdlus ja parima leidmine
function checkHands(discard) {
	var hands = new Array();
	var temp;
	
	for(var i = 1; i < 10; i++) {
		if(players[i-1].active && discard.indexOf(i) < 0) {
			temp = checkHand(i);
			temp.player_no = i;
			temp.equal = new Array();
			hands.push(temp);
		}
	}
	
	var best = findBestHand(hands);
	
	return best;
}

// funktsioon 21 võimaliku kombinatsiooni seast parima leidmiseks
function checkHand(player_no) {
	var pos = player_no - 1;
	var myCards = [game.deck.deck[pos], game.deck.deck[pos + 9], game.deck.deck[18], 
	               game.deck.deck[19], game.deck.deck[20], 
	               game.deck.deck[21], game.deck.deck[22]];

		var myHands = new Array();
		for(var i = 0; i < 3; i++) {
			for(var j = i + 1; j < 4; j++) {
				for(var k = j + 1; k < 5; k++) {
					for(var l = k + 1; l < 6; l++) {
						for(var m = l + 1; m < 7; m++) {
							myHands.push(gaga.createHand([
								[myCards[i].value, myCards[i].suit],
								[myCards[j].value, myCards[j].suit],
								[myCards[k].value, myCards[k].suit],
								[myCards[l].value, myCards[l].suit],
								[myCards[m].value, myCards[m].suit]
								]));
						}
					}
				}
			}
		}
			
		return findBestHand(myHands);
}

// funktsioon 21 võimaliku kombinatsiooni seast parima leidmiseks
function findBestHand(hands) {
	var fix = new Array();
	fix = hands;
	var bestHands = new Array();
	var max = 0;
	for(var i = 0; i < fix.length; i++) {
		if(fix[i].identify().rank > max) {
			max = fix[i].identify().rank;
		}
	}
	
	for(var i = 0; i < hands.length; i++) {
		if(hands[i].identify().rank == max) {
			bestHands.push(hands[i]);
		}
	}
	
	var best;
	if(bestHands.length > 1)
		best = breakTie(bestHands, max);
	else
		best = bestHands[0];
	
	return best;
}

// viikide murdmiseks
function breakTie(hands, type) {
	var best;
	switch(type) {
	case 0: best = breakHighCard(hands); // high card
		break;
	case 1: best = breakPair(hands); // pair
		break;
	case 2: best = breakPairs(hands);// 2 pair
		break;
	case 3: best = breakPair(hands);// 3 of a kind
		break;
	case 4: best = breakStraight(hands); // straight
		break;
	case 5: best = breakHighCard(hands); // flush
		break;
	case 6: best = breakFullHouse(hands);// full house
		break;
	case 7: best = breakPair(hands);// four of a kind
		break;
	case 8: best = breakStraight(hands); // straight flush
		break;
	default: // mingi jama
		break;
	}
	
	return best;
}

// leida, kumbal käel on parem high card
function compareHighCard(hand1, hand2) {
	for(var j = 4; j >= 0; j--) {
		if(parseInt(CARD_VALUE[hand1.cards[j].value]) > parseInt(CARD_VALUE[hand2.cards[j].value])) {
			return 1;
		} else if(parseInt(CARD_VALUE[hand1.cards[j].value]) < parseInt(CARD_VALUE[hand2.cards[j].value])) {
			return -1;
		}
	}
	return 0;
}

// high card võrdlemine
function breakHighCard(hands) {
	var best = hands[0];
	var res;
	for(var i = 1; i < hands.length; i++) {
		res = compareHighCard(best, hands[i]);
		if(res == -1) {
			best = hands[i];
		} else if(res == 0) {
			if('equal' in best) {
				best.equal.push(hands[i]);
			}
		}
	}
	return best;
}

// paaride võrdlus
function breakPair(hands) {
	var best = hands[0];
	var bestVal = findPair(hands[0]);
	var res;
	
	for(var i = 1; i < hands.length; i++) {
		if(findPair(hands[i]) > bestVal) {
			best = hands[i];
			bestVal = findPair(hands[i]);
		} else if(findPair(hands[i]) == bestVal) {
			res = compareHighCard(best, hands[i]);
			if(res == -1) {
				best = hands[i];
			} else if(res == 0) {
				if('equal' in best) {
					best.equal.push(hands[i]);
				}
			}
		}
	}
	
	return best;
}

// 2 paari võrdlus
function breakPairs(hands) {
	var best = hands[0];
	var pairs = findPairs(hands[0]);
	var bestHighPair = pairs[0];
	var bestLowPair = pairs[1];
	var temp;
	var res;
	
	for(var i = 1; i < hands.length; i++) {
		temp = findPairs(hands[i]);
		if(temp[0] > bestHighPair) {
			best = hands[i];
			bestHighPair = temp[0];
			bestLowPair = temp[1];
		} else if(temp[0] == bestHighPair && temp[1] > bestLowPair) {
			best = hands[i];
			bestLowPair = temp[1];
		} else if(temp[0] == bestHighPair && temp[1] == bestLowPair) {
			res = compareHighCard(best, hands[i]);
			if(res == -1) {
				best = hands[i];
			} else if(res == 0) {
				if('equal' in best) {
					best.equal.push(hands[i]);
				}
			}
		}
	}
	
	return best;
}

// täis majade võrdlus
function breakFullHouse(hands) {
	var best = hands[0];
	var values = findFullHouse(hands[0]);
	var bestTriple = values[0];
	var bestPair = values[1];
	var temp;
	
	for(var i = 1; i < hands.length; i++) {
		temp = findFullHouse(hands[i]);
		if(temp[0] > bestTriple) {
			best = hands[i];
			bestTriple = temp[0];
			bestPair = temp[1];
		} else if(temp[0] == bestTriple && temp[1] > bestPair) {
			best = hands[i];
			bestPair = temp[1];
		} else if(temp[0] == bestTriple && temp[1] == bestPair) {
			if('equal' in best) {
				best.equal.push(hands[i]);
			}
		}
	}
	
	return best;
}

// ridade võrdlus
function breakStraight(hands) {
	var best = hands[0];
	var res;
	for(var i = 1; i < hands.length; i++) {
		if(isAceLowStraight(best) && isAceLowStraight(hands[i])) {
			if('equal' in best) {
				best.equal.push(hands[i]);
			}
			continue;
		} else if(isAceLowStraight(best) && !isAceLowStraight(hands[i])){
			best = hands[i];
			continue;
		} else if(!isAceLowStraight(best) && isAceLowStraight(hands[i])){
			continue;
		}
		res = compareHighCard(best, hands[i]);
		if(res == -1) {
			best = hands[i];
		} else if(res == 0) {
			if('equal' in best) {
				best.equal.push(hands[i]);
			}
		}
	}
	return best;
}

// kas rida algab ässaga
function isAceLowStraight(hand) {
	if(parseInt(CARD_VALUE[hand.cards[0].value]) == 2 && parseInt(CARD_VALUE[hand.cards[4].value]) == 14)
		return true;
	return false;
}

// leiab paari ja tagastab selle väärtuse
function findPair(hand) {
	var prevVal = hand.cards[0].value;
	for(var i = 1; i < 5; i++) {
		if(hand.cards[i].value == prevVal)
			break;
		prevVal = hand.cards[i].value;
	}
	return parseInt(CARD_VALUE[prevVal]);
}

// leiab paarid ja tagastab nende väärtuse
function findPairs(hand) {
	var prevVal = hand.cards[4].value;
	var pairs = new Array(2);
	var index = 0;
	
	for(var i = 3; i >= 0; i--) {
		if(hand.cards[i].value == prevVal) {
			pairs[index] = parseInt(CARD_VALUE[prevVal]);
			index++;
		}	
		prevVal = hand.cards[i].value;
	}
	return pairs;
}

// leida täis maja kolmiku ja paari väärtused
function findFullHouse(hand) {
	var values = new Array(2);
	
	if(hand.cards[1].value == hand.cards[2].value) {
		values[0] = parseInt(CARD_VALUE[hand.cards[1].value]);
		values[1] = parseInt(CARD_VALUE[hand.cards[3].value]);
	} else {
		values[0] = parseInt(CARD_VALUE[hand.cards[3].value]);
		values[1] = parseInt(CARD_VALUE[hand.cards[1].value]);
	}
	
	return values;
}

// väljastab chippide pilte
function calculateChips(player_no, amount) {
	var playerBet = amount;
	var remainder = 0;
	var amounts = new Array(5);
	var divisors = [ 100, 25, 10, 5, 1 ];

	for ( var i = 0; i > -5; i--) {
		remainder = playerBet % divisors[i * -1];
		amounts[i + 4] = (playerBet - remainder) / divisors[i * -1];
		playerBet = remainder;
	}

	var newHtml = "";

	switch (amounts[0]) {
	case 1:
		newHtml = '<img class="chip bigshadow" src="images/nupud/zetoon_white.png"/>';
		break;
	case 2:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop2" src="images/nupud/zetoon_white.png"/>';
		break;
	case 3:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop3" src="images/nupud/zetoon_white.png"/>';
		break;
	case 4:
		newHtml = '<img class="chip bigshadow move-right" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow move-right ontop3" src="images/nupud/zetoon_white.png"/>\
			<img class="chip smallshadow ontop4" src="images/nupud/zetoon_white.png"/>';
		break;
	default:
		break;
	}

	if (amounts[1] > 0) {
		newHtml = newHtml
				+ '<img class="chip bigshadow" src="images/nupud/zetoon_red.png"/>';
	}

	if (amounts[2] == 1) {
		newHtml = newHtml
				+ '<img class="chip bigshadow" src="images/nupud/zetoon_blue.png"/>';
	} else if (amounts[2] == 2) {
		newHtml = newHtml
				+ '<img class="chip bigshadow move-right" src="images/nupud/zetoon_blue.png"/>\
				<img class="chip smallshadow ontop2" src="images/nupud/zetoon_blue.png"/>';
	}
	
	switch (amounts[3]) {
	case 1:
		newHtml = newHtml + '<img class="chip bigshadow" src="images/nupud/zetoon_green.png"/>';
		break;
	case 2:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow ontop2" src="images/nupud/zetoon_green.png"/>';
		break;
	case 3:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_green.png"/>\
		<img class="chip smallshadow ontop3" src="images/nupud/zetoon_green.png"/>';
		break;
	default:
		break;
	}
	
	switch (amounts[4]) {
	case 1:
		newHtml = newHtml + '<img class="chip bigshadow" src="images/nupud/zetoon_black.png"/>';
		break;
	case 2:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop2" src="images/nupud/zetoon_black.png"/>';
		break;
	case 3:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop3" src="images/nupud/zetoon_black.png"/>';
		break;
	case 4:
		newHtml = newHtml + '<img class="chip bigshadow move-right" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop2" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow move-right ontop3" src="images/nupud/zetoon_black.png"/>\
		<img class="chip smallshadow ontop4" src="images/nupud/zetoon_black.png"/>';
		break;
	default:
		break;
	}
	
	if(player_no == 0) {
		var invisible = '<img class="invisible" src="images/nupud/1x1.png"/>';
		newHtml = invisible + newHtml + invisible;
	}

	$('#chips' + player_no).html(newHtml);
}

// funktsioon mängu lõpetamiseks
function endGame() {
	$("#start").show();
	$("#end").hide();
	window.location.reload(true);
}

// mängija kliki või nupuvajutuse ootamine ja seejärel edasi liikumine
function commence() {
	if(allowClick) {
		allowClick = false;
		$("#info").css("visibility", "hidden");
		finishGame();
		$("#textarea").append("<font color=blue><b>New round has started."+"</b></font><br/>");
		$("#textarea").scrollTop($("#textarea")[0].scrollHeight);
	}
}
//tab
$(function() {
    var $items = $('#vtab>ul>li');
    $items.mouseover(function() {
        $items.removeClass('selected');
        $(this).addClass('selected');

        var index = $items.index($(this));
        $('#vtab>div').hide().eq(index).show();
    }).eq(1).mouseover();
});